<?php
// +----------------------------------------------------------------------
// | Created by PHPstorm: JRKAdmin框架 [ JRKAdmin ] 
// +----------------------------------------------------------------------
// | Copyright (c) 2019~2022 [LuckyHHY] All rights reserved.
// +----------------------------------------------------------------------
// | SiteUrl: http://www.luckyhhy.cn
// +----------------------------------------------------------------------
// | Author: LuckyHhy <jackhhy520@qq.com>
// +----------------------------------------------------------------------
// | Date: 2020/2/29 0029
// +----------------------------------------------------------------------
// | Description:  
// +----------------------------------------------------------------------

namespace app\admin\controller;

use app\admin\model\Uploads;
use Jrk\Zipdown;
use think\facade\Request;


class Upload extends AdminBase
{

    public function initialize()
    {
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->model=new Uploads();
        $this->del="附件";
    }


    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/29 0029
     * @name: index
     * @describe：获取分页数据
     */
    public function index()
    {
        $res=$this->model->getAdminPageData($this->param);

        $this->assign('data', $res->toArray());
        $this->assign('page', $res->render());

       return $this->fetch();
    }


    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/29 0029
     * @name: upFile
     * @describe：素材上传
     */
    public function upFile(){
        return $this->fetch();
    }


    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/1 0001
     * @name: getImages
     * @describe：获取图片
     */
    public function getImages(){

        $res=$this->model->GetImagesFiles();

        $this->assign('data', $res->toArray());

        $this->assign('page', $res->render());

        return $this->fetch();
    }


    /**
     * @return mixed
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/1 0001
     * @name: getFiles
     * @describe：获取文件素材
     */
    public function getFiles(){
        $res=$this->model->GetImagesFiles(2);

        $this->assign('data', $res->toArray());

        $this->assign('page', $res->render());

        return $this->fetch();
    }

    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/29 0029
     * @name: downImg
     * @describe：单个文件下载
     */
    public function downImg(){
        $id=input("id"); //文件路径
        $file=db("upload")->find($id);
        if (!$file){
            $this->redirect(url('admin/upload/index'));exit;
        }
        $file_name=$file['filename'];
        $file_path=ROOT_PATH.'public'.$file['file_path'];

        if(!file_exists($file_path)){
            $this->error("文件不存在");exit;
        }

        $file1=fopen($file_path,"r");
        Header("Content-type: application/octet-stream;charset=utf-8");
        Header("Accept-Ranges: bytes");
        header("Content-Length: " . filesize($file_path));//文件大小
        header('Content-Disposition:attachment;filename='.$file_name.'');
        ob_clean();
        flush();
        echo fread($file1,filesize($file_path)); //输出文件大小到浏览器
        fclose($file1);
        exit();
    }


    /**
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/2/29 0029
     * @name: downFiles
     * @describe：打包下载
     */
    public function downFiles(){
        $ids=$this->request->param("ids");
        try{
            $data=db("upload")->where("id",'in',$ids)->select();

            $down=new Zipdown(); //实例化下载类
            //下面是实例操作过程：
            //产生一个临时文件，用于缓存下载文件，这个目录不一定为空，查找php.ini 搜索upload_tmp_dir 填写相对于的路径就行
            $dfile = tempnam('/', 'tmp');
            $filename = date ( 'YmdHis' ) . ".zip"; // 最终生成的文件名（含路径）
            //p($picarray);die;
            foreach($data as $val){
                $down->add_file(file_get_contents(ROOT_PATH.'public'.$val['file_path']), iconv('UTF-8','gbk',$val['filename']));
            }
            $down->output($dfile);

            ob_clean();
            header('Pragma: public');
            header('Last-Modified:'.gmdate('D, d M Y H:i:s') . 'GMT');
            header('Cache-Control:no-store, no-cache, must-revalidate');
            header('Cache-Control:pre-check=0, post-check=0, max-age=0');
            header('Content-Transfer-Encoding:binary');
            header('Content-Encoding:none');
            header('Content-type:multipart/form-data');
            header('Content-Disposition:attachment; filename="'.$filename.'"'); //设置下载的默认文件名
            header('Content-length:'. filesize($dfile));

            $fp = fopen($dfile, 'r');
            while(connection_status() == 0 && $buf = @fread($fp, 8192)){
                echo $buf;
            }
            fclose($fp);
            @unlink($dfile);
            @flush();
            @ob_flush();
            ob_end_clean();
            exit();
            //打包下载结束
        }catch (\Exception $exception){
            $this->redirect(url('admin/upload/index'));
        }
    }



    /**
     * @return false|mixed|string
     * @author: LuckyHhy <jackhhy520@qq.com>
     * @date: 2020/3/11
     * @name: UpVideo
     * @describe:
     */
    public function UpVideo(){
        if ($_POST) {
            $file=Request::file("file");

            $info = $file->validate(['size' => 1 * 1024 * 1024 * 1024, 'ext' => "mp4,flv,3gp,mov,avi,rmvb,mkv,wmv"])->move(ROOT_PATH.'public'.DS_PROS.'upload'.DS_PROS."video");

            if ($info){
                $path = '/upload'.DS_PROS."video".DS_PROS.$info->getSaveName();

                $path = str_replace("\\", "/", $path);

                return json_encode(array("code" => 1, "path" => $path, "name" => $info->getSaveName()));
            }else{

                return json_encode(array("code" => 0,"msg"=>"上传有误，请检查服务器配置！"));
            }

        }

        return $this->fetch();
    }





}